import React, { Component } from 'react';
import { Tabs, Modal, Spin } from 'antd';
import axios from 'axios'
import qs from 'qs'
import './App.css';
import SellTicketItem from './SellTicketItem'
import Config from './config'
import { Link } from 'react-router-dom';

const TabPane = Tabs.TabPane;

class SellTicket extends Component {
  constructor(props) {
    super(props)
    this.state = {
      width: document.querySelector('body').offsetWidth,
      height: document.querySelector('body').offsetHeight,
      visible: false,
      loading: false,
      maxNumber: 10,//最大单次购买数量
      distributor: [],
      consumptionList: [],
      distributorId: '',//门票渠道
      n: 0,
      loading: true,
      payButton: false
    }
  }

  componentWillMount() {
    document.title = '景区二次消费项目预订'
  }

  componentDidMount() {
    let code = this.getQueryString('code')
    let openId = localStorage.getItem('openId')
    localStorage.setItem('code', code)
    code && !openId ? this.getOpenId(code) : null
    this.getDistributorAndConsumption()
  }

  getOpenId(code) {
    axios.get(`http://sjhh.stswat.com:8180/app/user/getOpenId.do?appid=${Config.WeiXin.AppId}&secret=${Config.WeiXin.AppSecret}&code=${code}&grant_type=authorization_code`,
    ).then(response => {
      let openId = response.data.data.openid || ''
      localStorage.setItem('openId', openId)
    }).catch(error => {
      console.log(error)
    })
  }

  //目标页（redirect_uri跳转页） 获取code，code来自页面返回，这个需要揣摩，隐藏的坑
  getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
  }

  getDistributorAndConsumption() {//获取门票渠道及二销项目
    axios.get(Config.Fetch.DistributorAndConsumption,
    ).then(response => {
      if (response.data.success) {
        let distributors = response.data.distributors
        let consumptionList = response.data.consumptionList
        this.setState({
          distributor: distributors,
          consumptionList: consumptionList,
          visible: true,
          loading: false,
          payButton: true
        }, () => {
          for (let i = 0; i < consumptionList.length; i++) {
            this.setState({
              [`num${i}`]: 1,//数量
              [`price${i}`]: consumptionList[i]['price'],//单价
              [`total${i}`]: consumptionList[i]['price'],//总价
              [`total${i}`]: consumptionList[i]['price'],//总价
            })
          }
        })
      }

    }).catch(error => {
      console.log(error)
    })
  }

  handleOk = (distributorId) => {
    this.setState({ distributorId });
    setTimeout(() => {
      this.setState({ loading: false, visible: false });
    }, 600);
  }

  handleCancel = () => {
    this.setState({ visible: false });
  }

  callback(key) {
    this.setState({ n: key })
  }

  channel() {
    let bgColor = ['#C993D7', '#47C6E9', '#69AFF3', '#F39C9C', '#6FE475', '#8CABB4', '#F0B338', '#AC79EC', '#7AD4A7', '#4abfc8', '#f691f5', '#e7ad7c', '#667bf0', '#7c66ec', '#3396b1', '#c6ab83', '#8e8acb', '#64b76a', '#c67cbd', '#fca24a']
    let distributor = this.state.distributor
    let distributorData = []
    for (let i = 0; i < distributor.length; i++) {
      distributorData.push(
        <button className="button" style={{ background: `${bgColor[i]}` }} onClick={this.handleOk.bind(this, distributor[i]['distributorId'])}>{distributor[i]['shortName']}</button>
      )
    }
    return distributorData
  }

  addSub(type, index) {
    let num = this.state[`num${index}`]
    let total = this.state[`total${index}`]
    let price = this.state[`price${index}`]
    let maxNumber = this.state.maxNumber
    if (type == 'add') {
      if (num < maxNumber) {
        this.setState({
          [`num${index}`]: parseInt(num) + 1,
          [`total${index}`]: (parseFloat(price) * (parseInt(num) + 1)).toFixed(2),
        })
      }
    } else {
      if (num > 1) {
        this.setState({
          [`num${index}`]: parseInt(num) - 1,
          [`total${index}`]: (parseFloat(price) * (parseInt(num) - 1)).toFixed(2),
        })
      }
    }
  }

  addSubtract(type, index) {
    let num = this.state[`num${index}`]
    if (num == null || num == '') {
      this.setState({ num: 1 }, () => {
        this.addSub(type, index)
      })
    } else {
      this.addSub(type, index)
    }
  }

  pay() {
    this.setState({ loading: true })
    let n = this.state.n
    let name = this.state.consumptionList
    let consumptionName = name[n]['consumptionName']
    let price = this.state[`price${n}`]
    let num = this.state[`num${n}`]
    let total = this.state[`total${n}`]
    let consumptionId = name[n]['consumptionId']
    let openId = localStorage.getItem('openId') || ''
    axios.get(Config.Fetch.placeWechatOrder + `?openId=${openId}&userType=2&distributorId=${this.state.distributorId}&singlePrice=${price}&num=${num}&consumptionId=${consumptionId}`,
    ).then(response => {
      if (response.data.success) {
        this.setState({ loading: false })
        let { code, state, orderTime, payWay } = response.data.data.order
        this.props.history.push(`/order/${consumptionName}|${num}|${total}|${code}|${state}|${orderTime}|${payWay}`)
      }

    }).catch(error => {
      console.log(error)
    })
  }

  render() {
    let { width, height, consumptionList, loading, payButton } = this.state
    return (
      <Spin tip="加载中..." spinning={loading}>
        <div className="App" >
          <div >
            {/* <h3 style={{ margin: '20px 0',float:'left' }}>景区二次消费项目</h3> */}
            <Link to={`order`} style={{ margin: '10px 0 20px', float: 'right' }}>我的订单</Link>
          </div>
          <div style={{ height: '64vh' }}>
            <Tabs defaultActiveKey="0" onChange={this.callback.bind(this)}>
              {
                consumptionList.map((item, index) => (
                  <TabPane tab={item.consumptionName} key={index} tabBarStyle={{ fontSize: 18, }}>
                    <SellTicketItem num={this.state[`num${index}`]} total={this.state[`total${index}`]} index={index} addSubtract={this.addSubtract.bind(this)} />
                  </TabPane>
                ))
              }
            </Tabs>
          </div>

          {
            payButton && <div style={{ textAlign: 'center' }}>
              <img src={require('./images/pay.png')} className='payButImg' onClick={this.pay.bind(this)} />
            </div>
          }

          <Modal
            title="小主，您的门票是在哪购买的呢？"
            visible={this.state.visible}
            closable={false}
            maskClosable={false}
            footer={null}
            onOk={this.handleOk}
            bodyStyle={{ padding: 4 }}
            onCancel={this.handleCancel}
          >
            {this.state.visible ? this.channel() : null}
          </Modal>
        </div>
      </Spin>
    );
  }
}

export default SellTicket;
